﻿using Currency.Infra.Caching.Configurations;
using StackExchange.Redis;
using System;

namespace Currency.Infra.Caching.RedisProvider
{
    public class RedisDatabase : IRedisDatabase
    {
        /// <summary>
        /// 配置
        /// </summary>
        private readonly ConnectionConfig _connectionConfig;

        /// <summary>
        /// 懒加载multiplexer
        /// </summary>
        private readonly Lazy<ConnectionMultiplexer> _connectionMultiplexer;

        public RedisDatabase(ConnectionConfig connectionConfig)
        {
            _connectionConfig = connectionConfig;
            _connectionMultiplexer = new Lazy<ConnectionMultiplexer>(CreateConnectionMultiplexer);
        }

        /// <summary>
        ///  获取数据库
        /// </summary>
        public IDatabase GetDatabase()
        {
            return _connectionMultiplexer.Value.GetDatabase();
        }

        /// <summary>
        /// 创建Redis连接
        /// </summary>
        /// <returns>返回multiplexer</returns>
        private ConnectionMultiplexer CreateConnectionMultiplexer()
        {
            if (string.IsNullOrWhiteSpace(_connectionConfig.ConnectionString))
            {
                var configurationOptions = new ConfigurationOptions
                {
                    //ConnectTimeout = ConnectionTimeout, //超时时间
                    User = _connectionConfig.Username,//用户名
                    Password = _connectionConfig.Password,//密码
                    //AllowAdmin = AllowAdmin,// 当为true时 ，可以使用一些被认为危险的命令
                    DefaultDatabase = _connectionConfig.DatabaseIndex, //默认数据库索引
                };
                var endPoints = _connectionConfig.Dbconfig;

                //configurationOptions.EndPoints.Add(endPoints.Host, endPoints.Port);

                return ConnectionMultiplexer.Connect(configurationOptions.ToString());
            }
            else
            {
                //var options = ConfigurationOptions.Parse(_connectionConfig.ConnectionString);
                return ConnectionMultiplexer.Connect(_connectionConfig.ConnectionString);
            }
        }
    }
}
